package com.wf.course.web.controller.comm;

import com.utils.page.PageBean;
import com.wf.course.model.ad.VipCard;
import com.wf.course.model.comm.GroupBuying;
import com.wf.course.model.course.CourseChapter;
import com.wf.course.model.course.CourseInfo;
import com.wf.course.service.ICourseInfoService;
import com.wf.course.service.IGroupBuyingService;
import com.wf.course.service.IVipCardService;
import com.wf.course.web.Constants;
import com.wf.course.web.OSSUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 团购功能
 */
@Controller
@RequestMapping("/groupbuying")
public class GroupBuyingController {

    private static Logger logger = LoggerFactory.getLogger(GroupBuyingController.class);

    @Autowired
    private IGroupBuyingService groupBuyingService;

    @Autowired
    private ICourseInfoService courseInfoService;

    @Autowired
    private IVipCardService vipCardService;

    @RequestMapping("/activityList")
    public ModelAndView activityList(Integer pageNo, Integer pageSize, GroupBuying groupBuying, ModelAndView mav) {
        try {
            PageBean<GroupBuying> pageBean = new PageBean<>(pageNo, pageSize);
            pageBean.setObj(groupBuying);
            pageBean.setUrl("groupbuying/activityList");
            groupBuyingService.activityList(pageBean);
            StringBuilder builder = new StringBuilder();
            for (Field f : groupBuying.getClass().getDeclaredFields()) {
                f.setAccessible(true);
                if (null != f.get(groupBuying) && StringUtils.isNotBlank(f.get(groupBuying).toString())) {
                    builder.append("&" + f.getName() + "=" + f.get(groupBuying));
                }
            }
            pageBean.setParams(builder.toString());
            mav.addObject("page", pageBean);
            mav.setViewName("/comm/groupbuying/activityList");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
        }
        return mav;
    }

    @RequestMapping("addOrUpdateActivity")
    public String addOrUpdateActivity(GroupBuying groupBuying) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            if (StringUtils.isNotBlank(groupBuying.getRangeTime())) {
                String[] rangeTime = groupBuying.getRangeTime().split(" - ");
                groupBuying.setStartTime((format.parse(rangeTime[0])));
                groupBuying.setEndTime((format.parse(rangeTime[1])));
            }
            switch (groupBuying.getType()) {
                case 1:
                    groupBuying.setForeignId(groupBuying.getCourseId());
                    break;
                case 3:
                    groupBuying.setForeignId(groupBuying.getCardId());
                    break;
            }
            if (groupBuying.getImgFile() != null && groupBuying.getImgFile().getSize() != 0) {
                if (groupBuying.getId() != null) {
                    GroupBuying gb = groupBuyingService.searchActivity(groupBuying.getId());
                    try {
                        if (StringUtils.isNotBlank(gb.getImg())) {
                            // 删除原来图片
                            OSSUtil.delete(gb.getImg(), Constants.IGM_BUCKET);
                        }
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                }
                // 重新上传
                String imgPath = "";
                try {
                    imgPath = OSSUtil.addFile(groupBuying.getImgFile(), "groupbuy", Constants.IGM_BUCKET);
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
                groupBuying.setImg(imgPath);
            }
            if (groupBuying.getSubimgFile() != null && groupBuying.getSubimgFile().getSize() != 0) {
                if (groupBuying.getId() != null) {
                    GroupBuying gb = groupBuyingService.searchActivity(groupBuying.getId());
                    try {
                        if (StringUtils.isNotBlank(gb.getSubimg())) {
                            // 删除原来图片
                            OSSUtil.delete(gb.getSubimg(), Constants.IGM_BUCKET);
                        }
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                }
                // 重新上传
                String imgPath = "";
                try {
                    imgPath = OSSUtil.addFile(groupBuying.getSubimgFile(), "groupbuy", Constants.IGM_BUCKET);
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
                groupBuying.setSubimg(imgPath);
            }
            if (groupBuying.getShareFile() != null && groupBuying.getShareFile().getSize() != 0) {
                if (groupBuying.getId() != null) {
                    GroupBuying gb = groupBuyingService.searchActivity(groupBuying.getId());
                    try {
                        if (StringUtils.isNotBlank(gb.getShareImg())) {
                            // 删除原来图片
                            OSSUtil.delete(gb.getShareImg(), Constants.IGM_BUCKET);
                        }
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                }
                // 重新上传
                String imgPath = "";
                try {
                    imgPath = OSSUtil.addFile(groupBuying.getShareFile(), "groupbuy_share", Constants.IGM_BUCKET);
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
                groupBuying.setShareImg(imgPath);
            }
            if (null != groupBuying.getId()) {
                groupBuyingService.updateActivity(groupBuying);
            } else {
                groupBuyingService.addActivity(groupBuying);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "redirect:/groupbuying/activityList";
    }

    @RequestMapping("/toAddOrUpdateActivity/{id}")
    public String toAddOrUpdateActivity(@PathVariable("id") Integer id, Model model) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<CourseInfo> courses = courseInfoService.queryCourses();
        model.addAttribute("courses", courses);
        List<VipCard> cards = vipCardService.queryVipCards();
        model.addAttribute("cards", cards);
        if (id > 0) {
            GroupBuying gb = groupBuyingService.searchActivity(id);
            if (gb.getStartTime() != null && gb.getEndTime() != null) {
                gb.setStartDate(format.format(gb.getStartTime()));
                gb.setEndDate(format.format(gb.getEndTime()));
            }
            model.addAttribute("activity", gb);
        }
        return "/comm/groupbuying/addOrUpdateActivity";
    }

    @RequestMapping("/deleteActivity/{id}")
    public String deleteGoods(@PathVariable("id") Integer id) {
        groupBuyingService.deleteActivity(id);
        return "redirect:/groupbuying/activityList";
    }

    @RequestMapping("/activityMemberList")
    public ModelAndView activityMemberList(Integer pageNo, Integer pageSize, GroupBuying groupBuying, ModelAndView mav) {
        try {
            PageBean<GroupBuying> pageBean = new PageBean<>(pageNo, pageSize);
            pageBean.setObj(groupBuying);
            pageBean.setUrl("groupbuying/activityMemberList");
            groupBuyingService.activityMemberList(pageBean);
            StringBuilder builder = new StringBuilder();
            for (Field f : groupBuying.getClass().getDeclaredFields()) {
                f.setAccessible(true);
                if (null != f.get(groupBuying) && StringUtils.isNotBlank(f.get(groupBuying).toString())) {
                    builder.append("&" + f.getName() + "=" + f.get(groupBuying));
                }
            }
            pageBean.setParams(builder.toString());
            mav.addObject("page", pageBean);
            mav.setViewName("/comm/groupbuying/activityMemberList");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
        }
        return mav;
    }

}